#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by PyCharm.
# @Project: Code_Clone_Detection_Educoder
# @File: clone_detector.py
# @Description: 
# @Time: 2018/12/12 15:47
# @Author: ljz

import datetime

import jpype

from CCDetector.utils import mysql_pool

mysql_operator = mysql_pool.MysqlPool()


def detect(code_a_line, code_b_line, code_a_row, code_b_row, code_a_time, code_b_time,
           user_a_id, user_b_id, file_a_path, file_b_path, query_id):
    class_sequence_alignment = jpype.JClass('com.clone.detection.SequenceAlignment')
    sequence_alignment = class_sequence_alignment()
    sequence_alignment.setParameter(code_a_line, code_b_line, code_a_row, code_b_row)
    sequence_alignment.alignment()
    create_result_report(sequence_alignment.getCodeAResult(), sequence_alignment.getCodeBResult(),
                         code_a_time, code_b_time, user_a_id, user_b_id, file_a_path, file_b_path, query_id)


def create_result_report(code_a_result, code_b_result, code_a_time, code_b_time,
                         user_a_id, user_b_id, file_a_path, file_b_path, query_id):
    code_a_result = code_a_result.split(',')
    code_b_result = code_b_result.split(',')

    if code_a_time > code_b_time:
        if float(code_a_result[2]) > 0.7:
            result = mysql_operator.select_all("""
            select line_code from educoder_code_clone.origin_code
            where query_id='{}' and user_id='{}' and file_path='{}' and row_num>='{}' and row_num<='{}'
            """.format(query_id, user_a_id, file_a_path, code_a_result[0], code_a_result[1]))
            origin_code_a = ''
            for i in result:
                origin_code_a += i[0]

            result = mysql_operator.select_all("""
            select line_code from educoder_code_clone.origin_code
            where query_id='{}' and user_id='{}' and file_path='{}' and row_num>='{}' and row_num<='{}'
            """.format(query_id, user_b_id, file_b_path, code_b_result[0], code_b_result[1]))
            origin_code_b = ''
            for i in result:
                origin_code_b += i[0]

            mysql_operator.insert("""
            insert into educoder_code_clone.result
            (query_id, user_id, file_path, file_content, passed_time,
            target_user_id, target_file_path, target_file_content, target_passed_time, rate, detect_time)
            values ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')
            """.format(query_id,
                       user_a_id, file_a_path, origin_code_a.replace('\'', '\\\''), code_a_time,
                       user_b_id, file_b_path, origin_code_b.replace('\'', '\\\''), code_b_time,
                       float(code_a_result[2]) * 100, datetime.datetime.now()))
    else:
        if float(code_b_result[2]) > 0.7:
            result = mysql_operator.select_all("""
            select line_code from educoder_code_clone.origin_code
            where query_id='{}' and user_id='{}' and file_path='{}' and row_num>='{}' and row_num<='{}'
            """.format(query_id, user_a_id, file_a_path, code_a_result[0], code_a_result[1]))
            origin_code_a = ''
            for i in result:
                origin_code_a += i[0]

            result = mysql_operator.select_all("""
            select line_code from educoder_code_clone.origin_code
            where query_id='{}' and user_id='{}' and file_path='{}' and row_num>='{}' and row_num<='{}'
            """.format(query_id, user_b_id, file_b_path, code_b_result[0], code_b_result[1]))
            origin_code_b = ''
            for i in result:
                origin_code_b += i[0]

            mysql_operator.insert("""
            insert into educoder_code_clone.result
            (query_id, user_id, file_path, file_content, passed_time,
            target_user_id, target_file_path, target_file_content, target_passed_time, rate, detect_time)
            values ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')
            """.format(query_id,
                       user_b_id, file_b_path, origin_code_b.replace('\'', '\\\''), code_b_time,
                       user_a_id, file_a_path, origin_code_a.replace('\'', '\\\''), code_a_time,
                       float(code_a_result[2]) * 100, datetime.datetime.now()))


def run(detect_sequence, query_id):
    if not jpype.isJVMStarted():
        jar_path = r'./CCDetector/utils'
        jpype.startJVM(jpype.get_default_jvm_path(), '-ea', '-Djava.ext.dirs=' + jar_path)

    for i in range(len(detect_sequence)):
        for j in range(i + 1, len(detect_sequence)):
            for file_a_path in detect_sequence[i][1:]:
                for file_b_path in detect_sequence[j][1:]:
                    if file_a_path == file_b_path:

                        code_a_line = ''
                        code_a_row = ''
                        code_a_time = ''
                        result = mysql_operator.select_all("""
                        select code_md5, row_num, passed_time from educoder_code_clone.info 
                        where query_id='{}' and user_id='{}' and file_path='{}'
                        """.format(query_id, detect_sequence[i][0], file_a_path))
                        for k in range(len(result)):
                            code_a_line += result[k][0]
                            code_a_row += str(result[k][1])
                            code_a_time = result[k][2]
                            if k < len(result) - 1:
                                code_a_line += ','
                                code_a_row += ','

                        code_b_line = ''
                        code_b_row = ''
                        code_b_time = ''
                        result = mysql_operator.select_all("""
                        select code_md5, row_num, passed_time from educoder_code_clone.info 
                        where query_id='{}' and user_id='{}' and file_path='{}'
                        """.format(query_id, detect_sequence[j][0], file_b_path))
                        for k in range(len(result)):
                            code_b_line += result[k][0]
                            code_b_row += str(result[k][1])
                            code_b_time = result[k][2]
                            if k < len(result) - 1:
                                code_b_line += ','
                                code_b_row += ','

                        detect(code_a_line, code_b_line, code_a_row, code_b_row, code_a_time, code_b_time,
                               detect_sequence[i][0], detect_sequence[j][0],
                               file_a_path, file_b_path, query_id)

                        break
